package org.jbch.shittim;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.RemoteException;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.jbch.shittim.ShittimInfo.DownloadState;

public class JbchAdapter extends ArrayAdapter<ShittimInfo> {
//	private Activity activity;
	private ArrayList<HashMap<String, String>> data;
	private static LayoutInflater inflater = null;
	public int currentPosition=-1;
	Handler ahandler;
	private int prvMidx = 0;
	  
	private static class ViewHolder {
		TextView id;
		TextView title;
		TextView pubdate;
//		TextView writer;
		ImageView thumb_image;
		LinearLayout thumb_bg;
		ImageView more_image;
	    ProgressBar progressBar;
	    ImageView downloadBtn;
		ShittimInfo info;
		} 
	

	
	private static final String TAG = JbchAdapter.class.getSimpleName();

//	  public DownloadInfoArrayAdapter(Context context, int textViewResourceId,List<DownloadInfo> objects) {
//	    super(context, textViewResourceId, objects);
//	  }
	public JbchAdapter(Context context, int textViewResourceId,List<ShittimInfo> objects) {
		super(context, textViewResourceId, objects); 
	} 

//	public long getItemId(int position) {
//		return position;
//	}
	
	// ListView에서 각 행(row)을 화면에 표시하기 전 호출됨.
	public View getView(int position, View convertView, ViewGroup parent) {
	    View row = convertView;
	    final ShittimInfo info = getItem(position);
	    
	    
	    
		ViewHolder holder; 
//		View vi = convertView;
		if (convertView == null){

			LayoutInflater inflater = (LayoutInflater) getContext()
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			row = inflater.inflate(R.layout.list_row, parent, false);
			holder = new ViewHolder();
			
			
			holder.id = (TextView) row.findViewById(R.id.board_id); // id
			holder.title = (TextView) row.findViewById(R.id.board_subject); // title
			holder.pubdate = (TextView) row.findViewById(R.id.board_date); // artist
			holder.thumb_image = (ImageView) row.findViewById(R.id.list_image); // thumb
			holder.thumb_bg = (LinearLayout) row.findViewById(R.id.linearLayout1); // thumb
			holder.more_image = (ImageView) row.findViewById(R.id.list_more_image); // thumb
			holder.progressBar = (ProgressBar) row.findViewById(R.id.downloadProgressBar);
			holder.downloadBtn = (ImageView)row.findViewById(R.id.downloadButton);
			
			holder.info = info;
			row.setTag(holder);
		}else{
			holder = (ViewHolder) row.getTag();
			holder.info.setProgressBar(null);
			holder.info = info;
			holder.info.setProgressBar(holder.progressBar);
		}

		holder.id.setText(info.getmId());
		holder.title.setText(info.getmTitle());
		holder.pubdate.setText(info.getmPubDate());

		holder.thumb_image.setImageResource(0);
		holder.thumb_bg.setBackgroundResource(R.drawable.thum_bg2);
		holder.more_image.setImageResource(R.drawable.ic_list_more);
		
	    holder.progressBar.setProgress(info.getProgress());
	    holder.progressBar.setMax(100);
	    info.setProgressBar(holder.progressBar);
	    holder.downloadBtn.setEnabled(info.getDownloadState() == DownloadState.NOT_STARTED);

		try {
			if(Utils.sService.getmBinder().getCurrentMidx()==position){

				if (Utils.sService.getmBinder().isPlaying()) {
					holder.thumb_image.setImageResource(R.drawable.on_play);
				} else {
					holder.thumb_image.setImageResource(R.drawable.on_play_disable);
				} 
				holder.thumb_image.refreshDrawableState();
				holder.thumb_image.invalidate();

				holder.thumb_bg.setBackgroundResource(R.drawable.thum_bg);
				holder.thumb_bg.refreshDrawableState();
				holder.thumb_bg.invalidate();

				holder.more_image.setImageResource(R.drawable.ic_list_more_selected);
				holder.more_image.refreshDrawableState();
				holder.more_image.invalidate();
			} 
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		final ImageView thumb_image = holder.thumb_image;
		holder.thumb_image.setOnClickListener(new imageViewClickListener(position, info.getmId(),info.getmDesc()));

		final ImageView downloadBtn = holder.downloadBtn;
		final ProgressBar progressbar = holder.progressBar;
	    holder.downloadBtn.setOnClickListener(new OnClickListener() {
		@SuppressLint("NewApi")
		@Override
	      public void onClick(View v) {
			Log.i("jbchLog","xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
//			progressbar.setVisibility(View.VISIBLE);
	        info.setDownloadState(DownloadState.QUEUED);
	        downloadBtn.setEnabled(false);
	        downloadBtn.invalidate();
	        FileDownloadTask task = new FileDownloadTask(info);
	        task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); 
	      }
	    });
		
		
		
		
		return row;
	}

	class imageViewClickListener implements OnClickListener {
		int position;
		String id;
		String desc;
		public imageViewClickListener(int pos , String id,String desc) {
			this.position = pos;
			this.id=id;
			this.desc=desc;
		}
  
		public void onClick(View v) {
 
			// 클릭 전에 저장되어 있던 row index 값 
			try {
				prvMidx = Utils.sService.getmBinder().getCurrentMidx();
				// 클릭한 row index 값으로 다시 저장
				Utils.sService.getmBinder().setCurrentMidx(this.position);
			} catch (RemoteException e1) {
				e1.printStackTrace();
			} 
			
			int resId=0;	 
			try { 
				// 플레이 중일 경우
				if (Utils.sService.getmBinder().isPlaying()) {

					// 같은 row를 클릭했을 때 
					if(prvMidx == this.position){
						resId = R.drawable.on_play_disable;
						Utils.sService.getmBinder().pause();
					}else{
						resId = R.drawable.on_play;
						Utils.sService.getmBinder().reset();
						Utils.sService.getmBinder().playFile(this.position);
					}
					  
				} else {
					// 같은 row를 클릭했을 때 
					if(prvMidx == this.position){
						resId = R.drawable.on_play;
						Utils.sService.getmBinder().start();
					}else{
						resId = R.drawable.on_play;
						Utils.sService.getmBinder().reset();
						Utils.sService.getmBinder().playFile(this.position);
					}
				}

				Intent intent2 = new Intent(BackgroundAudioService.ACTION_BROAD_PLAY_STATE);
				// 플레이 중일 경우
				if (Utils.sService.getmBinder().isPlaying()) {
					intent2.putExtra("state", 1);
				}else{  
					intent2.putExtra("state", 0);
				}    
				getContext().sendBroadcast(intent2);

				Intent intent = new Intent(BackgroundAudioService.ACTION_BROAD_PLAY_ON_LIST);
				
				intent.putExtra("arryIdx", this.position);  
				intent.putExtra("resId", resId); 
				getContext().sendBroadcast(intent);
				
			} catch (RemoteException e) {
				e.printStackTrace();
			}

		}
 
	}
}
